package com.uduemc.biso.node.module.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.module.service.SCategoriesService;

@RestController
@RequestMapping("/s-categories")
public class SCategoriesController {

	private static final Logger logger = LoggerFactory.getLogger(SCategoriesController.class);

	@Autowired
	private SCategoriesService sCategoriesServiceImpl;

	@PostMapping("/insert")
	public RestResult insert(@Valid @RequestBody SCategories sCategories, BindingResult errors) {
		logger.info("insert: " + sCategories.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}
		SCategories data = sCategoriesServiceImpl.insert(sCategories);
		return RestResult.ok(data, SCategories.class.toString());
	}

	@PutMapping("/update-by-id")
	public RestResult updateById(@Valid @RequestBody SCategories sCategories, BindingResult errors) {
		logger.info("updateById: " + sCategories.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}
		SCategories findOne = sCategoriesServiceImpl.findOne(sCategories.getId());
		if (findOne == null) {
			return RestResult.noData();
		}
		SCategories data = sCategoriesServiceImpl.updateById(sCategories);
		return RestResult.ok(data, SCategories.class.toString());
	}

	@GetMapping("/find-one/{id:\\d+}")
	public RestResult findOne(@PathVariable("id") Long id) {
		SCategories data = sCategoriesServiceImpl.findOne(id);
		if (data == null) {
			return RestResult.noData();
		}
		return RestResult.ok(data, SCategories.class.toString());
	}

	@GetMapping(value = { "/find-all" })
	public RestResult findAll(@PageableDefault(page = 0, size = 12) Pageable pageable) {
		logger.info("pageable: " + pageable.toString());
		List<SCategories> findAll = sCategoriesServiceImpl.findAll(pageable);
		return RestResult.ok(findAll, SCategories.class.toString(), true);
	}

	@GetMapping("/delete-by-id/{id:\\d+}")
	public RestResult deleteById(@PathVariable("id") Long id) {
		SCategories findOne = sCategoriesServiceImpl.findOne(id);
		if (findOne == null) {
			return RestResult.ok();
		}
		sCategoriesServiceImpl.deleteById(id);
		return RestResult.ok(findOne);
	}

	/**
	 * 通过hostId获取数据总数
	 * 
	 * @param hostId
	 * @return
	 */
	@GetMapping("/total-by-host-id/{hostId:\\d+}")
	public RestResult totalByHostId(@PathVariable("hostId") Long hostId) {
		int total = sCategoriesServiceImpl.totalByHostId(hostId);
		return RestResult.ok(total, Integer.class.toString());
	}

	/**
	 * 通过siteId获取数据总数
	 * 
	 * @param siteId
	 * @return
	 */
	@GetMapping("/total-by-site-id/{siteId:\\d+}")
	public RestResult totalBySiteId(@PathVariable("siteId") Long siteId) {
		int total = sCategoriesServiceImpl.totalBySiteId(siteId);
		return RestResult.ok(total, Integer.class.toString());
	}

	/**
	 * 通过systemId获取数据总数
	 * 
	 * @param systemId
	 * @return
	 */
	@GetMapping("/total-by-system-id/{systemId:\\d+}")
	public RestResult totalBySystemId(@PathVariable("systemId") Long systemId) {
		int total = sCategoriesServiceImpl.totalBySystemId(systemId);
		return RestResult.ok(total, Integer.class.toString());
	}

	/**
	 * 通过hostId、siteId获取数据总数
	 * 
	 * @param systemId
	 * @return
	 */
	@GetMapping("/total-by-host-site-id/{hostId:\\d+}/{siteId:\\d+}")
	public RestResult totalByHostSiteId(@PathVariable("hostId") Long hostId, @PathVariable("siteId") Long siteId) {
		int total = sCategoriesServiceImpl.totalByHostSiteId(hostId, siteId);
		return RestResult.ok(total, Integer.class.toString());
	}

	/**
	 * 通过hostId、siteId、systemId获取数据总数
	 * 
	 * @param systemId
	 * @return
	 */
	@GetMapping("/total-by-host-site-system-id/{hostId:\\d+}/{siteId:\\d+}/{systemId:\\d+}")
	public RestResult totalByHostSiteSystemId(@PathVariable("hostId") Long hostId, @PathVariable("siteId") Long siteId,
			@PathVariable("systemId") Long systemId) {
		int total = sCategoriesServiceImpl.totalByHostSiteSystemId(hostId, siteId, systemId);
		return RestResult.ok(total, Integer.class.toString());
	}

	/**
	 * 通过hostId、siteId、systemId获取分类数据
	 * 
	 * @param hostId
	 * @param siteId
	 * @param systemId
	 * @return
	 */
	@GetMapping("/find-by-host-site-system-id/{hostId:\\d+}/{siteId:\\d+}/{systemId:\\d+}")
	public RestResult findByHostSiteSystemId(@PathVariable("hostId") Long hostId, @PathVariable("siteId") Long siteId,
			@PathVariable("systemId") Long systemId) {
		return RestResult.ok(sCategoriesServiceImpl.findByHostSiteSystemId(hostId, siteId, systemId), SCategories.class.toString(), true);
	}

	/**
	 * 通过hostId、siteId、systemId、pageSize、orderBy获取分类数据
	 * 
	 * @param hostId
	 * @param siteId
	 * @param systemId
	 * @return
	 */
	@PostMapping("/find-by-host-site-system-id-page-size-order-by")
	public RestResult findByHostSiteSystemIdPageSizeOrderBy(@RequestParam("hostId") long hostId, @RequestParam("siteId") long siteId,
			@RequestParam("systemId") long systemId, @RequestParam("pageSize") int pageSize, @RequestParam("orderBy") String orderBy) {
		return RestResult.ok(sCategoriesServiceImpl.findByHostSiteSystemIdPageSizeOrderBy(hostId, siteId, systemId, pageSize, orderBy),
				SCategories.class.toString(), true);
	}

	/**
	 * 删除通过分类ID删除分类，并且删除分类中的引用数据
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/delete-category-by-id/{id:\\d+}")
	public RestResult deleteCategoryById(@PathVariable("id") Long id) {
		SCategories findOne = sCategoriesServiceImpl.findOne(id);
		if (findOne == null) {
			return RestResult.ok();
		}
		boolean deleteSystemById = sCategoriesServiceImpl.deleteBySCategories(findOne);
		if (!deleteSystemById) {
			return RestResult.error();
		}
		return RestResult.ok(findOne);
	}

	/**
	 * 删除通过分类id、hostId、siteId删除分类，并且删除分类中的引用数据
	 * 
	 * @param id
	 * @param hostId
	 * @param siteId
	 * @return
	 */
	@GetMapping("/delete-category-by-id-host-site-id/{id:\\d+}/{hostId:\\d+}/{siteId:\\d+}")
	public RestResult deleteCategoryByIdHostSiteId(@PathVariable("id") long id, @PathVariable("hostId") long hostId, @PathVariable("siteId") long siteId) {
		SCategories findOne = sCategoriesServiceImpl.findByIdHostSiteId(id, hostId, siteId);
		if (findOne == null) {
			return RestResult.ok();
		}
		boolean deleteSystemById = sCategoriesServiceImpl.deleteBySCategories(findOne);
		if (!deleteSystemById) {
			return RestResult.error();
		}
		return RestResult.ok(findOne);
	}

	/**
	 * 通过查找传入 sCategories 的 parentId 同一级别的最大 order_num ，然后在此 order_num 加1写入数据库中
	 * 
	 * @param sCategories
	 * @param errors
	 * @return
	 */
	@PostMapping("/insert-append-order-num")
	public RestResult insertAppendOrderNum(@Valid @RequestBody SCategories sCategories, BindingResult errors) {
		logger.info("insert: " + sCategories.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}
		SCategories data = sCategoriesServiceImpl.insertAppendOrderNum(sCategories);
		return RestResult.ok(data, SCategories.class.toString());
	}

	/**
	 * 通过 id 找出所有的子级
	 * 
	 * @param parentId
	 * @return
	 */
	@GetMapping("/find-by-parent-id/{id:\\d+}")
	public RestResult findByParentId(@PathVariable("id") long id) {
		List<SCategories> data = sCategoriesServiceImpl.findByParentId(id);
		return RestResult.ok(data, SCategories.class.toString(), true);
	}

	/**
	 * 通过id找出所有的子级以及子级的子级递归的形式找出所有的结果
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/find-by-ancestors/{id:\\d+}")
	public RestResult findByAncestors(@PathVariable("id") long id) {
		List<SCategories> data = sCategoriesServiceImpl.findByAncestors(id);
		return RestResult.ok(data, SCategories.class.toString(), true);
	}

	/**
	 * 通过 id 找出所有的子级然后进行删除
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/delete-by-parent-id/{id:\\d+}")
	public RestResult deleteByParentId(@PathVariable("id") long id) {
		List<SCategories> data = sCategoriesServiceImpl.findByParentId(id);
		return RestResult.ok(sCategoriesServiceImpl.deleteByList(data), Boolean.class.toString());
	}

	/**
	 * 通过id找出所有的子级以及子级的子级递归的形式找出所有的结果然后进行删除
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/delete-by-ancestors/{id:\\d+}")
	public RestResult deleteByAncestors(@PathVariable("id") long id) {
		List<SCategories> data = sCategoriesServiceImpl.findByAncestors(id);
		return RestResult.ok(sCategoriesServiceImpl.deleteByList(data), Boolean.class.toString());
	}

	/**
	 * 通过 hostId、siteId 判断 list的 categoryIds 所有的 ID 是否可用
	 * 
	 * @param hostId
	 * @param siteId
	 * @param categoryIds
	 * @return
	 */
	@PostMapping("/exist-by-host-site-list-category-id")
	public RestResult existByHostSiteListCagetoryIds(@RequestParam("hostId") long hostId, @RequestParam("siteId") long siteId,
			@RequestParam("categoryIds") List<Long> categoryIds) {
		return RestResult.ok(sCategoriesServiceImpl.existByHostSiteListCagetoryIds(hostId, siteId, categoryIds), Boolean.class.toString());
	}

	/**
	 * 通过 hostId、siteId、systemId 判断 list的 categoryIds 所有的 ID 是否可用
	 * 
	 * @param hostId
	 * @param siteId
	 * @param systemId
	 * @param categoryIds
	 * @return
	 */
	@PostMapping("/exist-by-host-site-system-category-ids")
	public RestResult existByHostSiteSystemCagetoryIds(@RequestParam("hostId") long hostId, @RequestParam("siteId") long siteId,
			@RequestParam("systemId") long systemId, @RequestParam("categoryIds") List<Long> categoryIds) {
		return RestResult.ok(sCategoriesServiceImpl.existByHostSiteSystemCagetoryIds(hostId, siteId, systemId, categoryIds), Boolean.class.toString());
	}

	/**
	 * 通过id找出所有的子级以及子级的子级递归的形式找出所有的结果
	 * 
	 * @param hostId
	 * @param siteId
	 * @param id
	 * @return
	 */
	@GetMapping("/find-by-host-site-id-and-id/{hostId:\\d+}/{siteId:\\d+}/{id:\\d+}")
	public RestResult findByHostSiteIdAndId(@PathVariable("hostId") long hostId, @PathVariable("siteId") long siteId, @PathVariable("id") long id) {
		SCategories data = sCategoriesServiceImpl.findByHostSiteIdAndId(hostId, siteId, id);
		if (data == null) {
			return RestResult.noData();
		}
		return RestResult.ok(data, SCategories.class.toString());
	}

	/**
	 * 通过 hostId、siteId、rewrite 获取到一条分类数据
	 * 
	 * @param hostId
	 * @param siteId
	 * @param id
	 * @return
	 */
	@GetMapping("/find-by-host-site-id-and-rewrite/{hostId:\\d+}/{siteId:\\d+}/{rewrite}")
	public RestResult findByHostSiteIdAndRewrite(@PathVariable("hostId") long hostId, @PathVariable("siteId") long siteId,
			@PathVariable("rewrite") String rewrite) {
		SCategories data = sCategoriesServiceImpl.findByHostSiteIdAndRewrite(hostId, siteId, rewrite);
		if (data == null) {
			return RestResult.noData();
		}
		return RestResult.ok(data, SCategories.class.toString());
	}
}
